package com.ibeetl.cms.web;

import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.file.FileService;
import com.ibeetl.admin.core.service.CorePlatformService;
import com.ibeetl.admin.core.util.ConvertUtil;
import com.ibeetl.admin.core.util.ValidateConfig;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.cms.entity.Enterprise;
import com.ibeetl.cms.entity.Entry;
import com.ibeetl.cms.entity.EssentialInformation;
import com.ibeetl.cms.service.BusinessProcessService;
import com.ibeetl.cms.service.EnterpriseService;
import com.ibeetl.cms.service.EntryService;
import com.ibeetl.cms.service.EssentialInformationService;
import com.ibeetl.cms.util.BusinessTypeConstant;
import com.ibeetl.cms.util.ProcessConstant;
import com.ibeetl.cms.web.query.EntryQuery;
import com.ibeetl.cms.web.query2.EntryEnterpriseQuery;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * Entry 接口
 */
@Controller
public class EntryController{

    private final Log log = LogFactory.getLog(this.getClass());
    private static final String MODEL = "/cms/entry";

    @Autowired
    CorePlatformService platformService;

    @Autowired private EntryService entryService;

    @Autowired
    private EssentialInformationService essentialInformationService;


    @Autowired
    FileService fileService;

    @Autowired
    private BusinessProcessService businessProcessService;

    @Autowired private EnterpriseService enterpriseService;
    /* 页面 */

    @GetMapping(MODEL + "/index.do")
    @Function("entry")
    @ResponseBody
    public ModelAndView index() {
        ModelAndView view = new ModelAndView("/cms/entry/index.html") ;
        view.addObject("search", EntryQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/enterprise.do")
    @Function("entry.company")
    @ResponseBody
    public ModelAndView enterprise() {
        ModelAndView view = new ModelAndView("/cms/entry/enterprise.html") ;
        view.addObject("search", EntryEnterpriseQuery.class.getName());
        return view;
    }

    @GetMapping(MODEL + "/edit.do")
    @Function("entry")
    @ResponseBody
    public ModelAndView edit(Integer id) {
        ModelAndView view = new ModelAndView("/cms/entry/edit.html");
        Entry entry = entryService.queryById(id);
        List<Enterprise> enterprises=enterpriseService.findAll();
        view.addObject("enterprise", enterprises);
        view.addObject("entry", entry);
        return view;
    }

    @GetMapping(MODEL + "/add.do")
    @Function("entry")
    @ResponseBody
    public ModelAndView add() {
        ModelAndView view = new ModelAndView("/cms/entry/add.html");
        Long userid = getUserId();
        EssentialInformation essentialInformation = essentialInformationService.finduserid(userid);
        List<Enterprise> enterprises=enterpriseService.findAll();
        view.addObject("basic", essentialInformation);
        view.addObject("enterprise", enterprises);
        return view;
    }

    /* ajax json */

    @PostMapping(MODEL + "/list.json")
    @Function("entry")
    @ResponseBody
    public JsonResult<PageQuery> list(EntryQuery condtion)
    {
        PageQuery page = condtion.getPageQuery();
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        condtion.setYear( year.toString());
        condtion.setUserId(getUserId());
        entryService.queryByCondition(page);
        return JsonResult.success(page);
    }

    @PostMapping(MODEL + "/Acceptancelist.json")
    @Function("entry.company")
    @ResponseBody
    public JsonResult<PageQuery> Acceptancelist(EntryQuery condtion)
    {
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        condtion.setYear( year.toString());
        condtion.setUserId(getUserId());

        condtion.setCompanyId(getUserId().toString());
        if(condtion.getBusinessState()=="" || condtion.getBusinessState()==null){
            condtion.setBusinessState(ProcessConstant.TO_COMPANY);
        }else {
            condtion.setBusinessState(condtion.getBusinessState());
        }
        //查询企业数据
        PageQuery page = condtion.getPageQuery();
        entryService.findenterprise(page);
        return JsonResult.success(page);
    }

    /**
     * 新增（保存并申请）
     *
     * @param entry
     * @return
     */
    @PostMapping(MODEL + "/savedeclaration.json")
    @Function("entry")
    @ResponseBody
    public JsonResult savedeclaration(@Validated(ValidateConfig.ADD.class) Entry entry) {
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();
        
        entry.setUserId(getUserId().intValue());
        entry.setBusinessState(ProcessConstant.TO_COMPANY_STR);
        entry.setBusinessStateCode(ProcessConstant.TO_COMPANY);
        entry.setYear(yearStr);

        entry.setCreationDate(new Date());
        entry.setDateReporting(new Date());

        entryService.save(entry);

        //调用增加业务流程数据
        businessProcessService.processInformation(entry.getId(),entry.getBusinessState(),
                entry.getBusinessStateCode(),entry.getHandlingSuggestion(),"成功",
                BusinessTypeConstant.entry);
        return new JsonResult().success();
    }

    /**
     * 新增（保存）
     * @param entry
     * @return
     */
    @PostMapping(MODEL + "/add.json")
    @Function("entry")
    @ResponseBody
    public JsonResult add(@Validated(ValidateConfig.ADD.class)Entry entry)
    {
        Integer year = Calendar.getInstance().get(Calendar.YEAR);
        String yearStr = year.toString();
        entry.setYear(yearStr);

        entry.setUserId(getUserId().intValue());
        entry.setBusinessState(ProcessConstant.WAIT_APPLICATION_STR);
        entry.setBusinessStateCode(ProcessConstant.WAIT_APPLICATION);

        entry.setCreationDate(new Date());

        entryService.save(entry);
        //调用增加业务流程数据
        businessProcessService.processInformation(entry.getId(),entry.getBusinessState(),
                entry.getBusinessStateCode(),entry.getHandlingSuggestion(),"成功"
        ,BusinessTypeConstant.entry);
        return new JsonResult().success();
    }

    /**
     * 修改（保存并申请）
     *
     * @param entry
     * @return
     */
    @PostMapping(MODEL + "/editandsave.json")
    @Function("entry")
    @ResponseBody
    public JsonResult<String> editandsave(@Validated(ValidateConfig.UPDATE.class)  Entry entry) {
        entry.setDateReporting(new Date());

        entry.setBusinessState(ProcessConstant.TO_COMPANY_STR);
        entry.setBusinessStateCode(ProcessConstant.TO_COMPANY);

        boolean success = entryService.updateTemplate(entry);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }

    /**
     * 修改（保存）
     * @param entry
     * @return
     */
    @PostMapping(MODEL + "/update.json")
    @Function("entry")
    @ResponseBody
    public JsonResult<String> update(@Validated(ValidateConfig.UPDATE.class)  Entry entry) {
        entry.setBusinessState(ProcessConstant.WAIT_APPLICATION_STR);
        entry.setBusinessStateCode(ProcessConstant.WAIT_APPLICATION);

        boolean success = entryService.updateTemplate(entry);
        if (success) {
            return new JsonResult().success();
        } else {
            return JsonResult.failMessage("保存失败");
        }
    }


   
    @GetMapping(MODEL + "/view.json")
    @Function("cms.entry.query")
    @ResponseBody
    public JsonResult<Entry>queryInfo(Integer id) {
        Entry entry = entryService.queryById( id);
        return  JsonResult.success(entry);
    }

    @PostMapping(MODEL + "/delete.json")
    @Function("entry")
    @ResponseBody
    public JsonResult delete(String ids) {
        if (ids.endsWith(",")) {
            ids = StringUtils.substringBeforeLast(ids, ",");
        }
        List<Long> idList = ConvertUtil.str2longs(ids);
        entryService.batchDelEntry(idList);
        return new JsonResult().success();
    }

    /**
     * 查看页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/findenterprise.do")
    @ResponseBody
    public ModelAndView findenterprise(Integer id) {
        ModelAndView view = new ModelAndView("/cms/entry/findenterpriseedit.html");
        Entry entry = entryService.queryById(id);
        view.addObject("look",true);
        view.addObject("entry", entry);
        return view;
    }

    @PostMapping(MODEL + "/firstcheckList.json")
    @ResponseBody
    public JsonResult<PageQuery> firstcheckList(EntryQuery condtion) {
        /**
         * 获得本年度已办任务
         */
        if(condtion.getYear()=="" || condtion.getYear()==null) {
            Integer year = Calendar.getInstance().get(Calendar.YEAR);
            condtion.setYear(year.toString());
        }
        condtion.setProcessUserId(getUserId());
        condtion.setBusinessType(BusinessTypeConstant.entry);
        PageQuery page = condtion.getPageQuery();
        entryService.queryDoneTask(page);
        return JsonResult.success(page);
    }

    /**
     * 单位产业人才点击受理页面跳转
     *
     * @return
     */
    @GetMapping(MODEL + "/acceptance.do")
    @Function("entry.company")
    @ResponseBody
    public ModelAndView acceptance(Integer id) {
        ModelAndView view = new ModelAndView("/cms/entry/acceptance.html");
        Entry entry = entryService.queryById(id);
        view.addObject("entry", entry);
        return view;
    }

    /**
     * 终止功能
     */
    @PostMapping(MODEL + "/Acceptancelisttermination.json")
    @Function("entry.company")
    @ResponseBody
    public JsonResult<String> Acceptancelisttermination(@Validated(ValidateConfig.UPDATE.class) Entry entry) {
        entry.setBusinessState(ProcessConstant.TERMINIATE_STR);
        entry.setBusinessStateCode(ProcessConstant.TERMINIATE);
        boolean success = entryService.updateTemplate(entry);
        String result;
        if (success) {
            result=ProcessConstant.TERMINIATE_STR;
        } else {
            result="失败";
        }
        //调用增加业务流程数据
        businessProcessService.processInformation(entry.getId(),entry.getBusinessState(),
                entry.getBusinessStateCode(),entry.getHandlingSuggestion(),result,BusinessTypeConstant.entry);
        return new JsonResult().success();
    }

    /**
     * 退回功能
     */
    @PostMapping(MODEL + "/Acceptancelistterreturn.json")
    @Function("entry.company")
    @ResponseBody
    public JsonResult<String> Acceptancelistterreturn(@Validated(ValidateConfig.UPDATE.class) Entry entry) {
            entry.setBusinessState(ProcessConstant.RETURN_DECLARATION_STR);
            entry.setBusinessStateCode(ProcessConstant.RETURN_DECLARATION);
        boolean success = entryService.updateTemplate(entry);
        String result;
        if (success) {
            result=ProcessConstant.COMPANY_BACK_STR;
        } else {
            result="失败";
        }
        //调用增加业务流程数据
        businessProcessService.processInformation(entry.getId(),entry.getBusinessState(),
                entry.getBusinessStateCode(),entry.getHandlingSuggestion(),result,BusinessTypeConstant.entry);
        return new JsonResult().success();
    }

    /**
     * 通过功能
     */
    @PostMapping(MODEL + "/Acceptancelistsuccess.json")
    @Function("entry.company")
    @ResponseBody
    public JsonResult<String> Acceptancelistsuccess(@Validated(ValidateConfig.UPDATE.class) Entry entry) {
            entry.setBusinessState(ProcessConstant.DONE_STR);
            entry.setBusinessStateCode(ProcessConstant.DONE);
        boolean success = entryService.updateTemplate(entry);
        String result;
        if (success) {
            entryService.updateCompanyId(entry.getCompanyId(),entry.getUserId());//修改用户表的公司Id
            //修改user_id修改个人基本信息表的公司ID和公司名
            entryService.updateEssentialInformation(entry.getCompanyId(),entry.getEntryUnit(),entry.getUserId());
            result=ProcessConstant.COMPANY_ADOPT_STR;
        } else {
            result="失败";
        }
        //调用增加业务流程数据
        businessProcessService.processInformation(entry.getId(),entry.getBusinessState(),
                entry.getBusinessStateCode(),entry.getHandlingSuggestion(),result,BusinessTypeConstant.entry);
        return new JsonResult().success();
    }


    /**
     * 公共方法
     * 用于获取登录ID
     *
     * @return
     */
    public Long getUserId() {
        CoreUser currentUser = platformService.getCurrentUser();
        Long userId = currentUser.getId();
        return userId;
    }
}
